from datetime import datetime, time

from Tools.demo.sortvisu import Array
from sqlalchemy import and_, delete, func, select, update
from sqlalchemy.ext.asyncio import AsyncSession
from module_admin.entity.do.rule_do import RuleMonitor
from module_admin.entity.vo.rule_vo import RulePageQueryModel, RuleModel
from utils.page_util import PageUtil


class RuleDao:

    @classmethod
    async def get_rule_monitor_list(cls, db: AsyncSession, query_object: RulePageQueryModel, is_page: bool = False):
        query = (
            select(RuleMonitor)
            .where(
                RuleMonitor.rule_id == query_object.rule_id if query_object.rule_id else True,
                RuleMonitor.status == query_object.status if query_object.status else True,
                RuleMonitor.schema_name.like(f'%{query_object.schema_name}%') if query_object.schema_name else True,
                RuleMonitor.create_by.like(f'%{query_object.create_by}%') if query_object.create_by else True,
                RuleMonitor.create_time.between(
                    datetime.combine(datetime.strptime(query_object.begin_time, '%Y-%m-%d'), time(00, 00, 00)),
                    datetime.combine(datetime.strptime(query_object.end_time, '%Y-%m-%d'), time(23, 59, 59)),
                )
                if query_object.begin_time and query_object.end_time
                else True,
            )
            .distinct()
        )
        rule_type_list = await PageUtil.paginate(db, query, query_object.page_num, query_object.page_size, is_page)

        return rule_type_list

    @classmethod
    async def get_rule_detail_by_id(cls, db: AsyncSession, rule_id: int):

        rule_info = (await db.execute(select(RuleMonitor).where(RuleMonitor.rule_id == rule_id))).scalars().first()

        return rule_info

    @classmethod
    async def add_rule_monitor_dao(cls, db: AsyncSession, rule_model: RuleModel):
        db_rule = RuleMonitor(**rule_model.model_dump())
        db.add(db_rule)

    @classmethod
    async def edit_rule_monitor_dao(cls, db: AsyncSession, rule: dict):
        await db.execute(update(RuleMonitor), [rule])

    @classmethod
    async def delete_rule_monitor_dao(cls, db: AsyncSession, rule_ids: list[int]):
        await db.execute(delete(RuleMonitor).where(RuleMonitor.rule_id.in_(rule_ids)))
